package com.monolithiot.sso.common.util;

/**
 * 2018/11/15 Create by 郭文梁
 * IdCardUtil
 * 身份证号工具类
 *
 * @author 郭文梁
 * @date 2018/11/15
 */
public class IdCardUtil {
    /**
     * 身份证号长度
     */
    private static final int ID_NUMBER_LENGTH = 18;
    private static final int[] NUMBER_WEIGHT = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    private static final char[] MOD_MAP = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
    private static final int CHAR_AND_NUMBER_OFFSET = -0x30;

    /**
     * 验证身份证号是否有效
     *
     * @param idNumber 身份证号
     * @return 是否有效
     */
    public static boolean validate(String idNumber) {
        if (idNumber == null) {
            return false;
        }
        char[] chars = idNumber.toCharArray();
        if (chars.length != ID_NUMBER_LENGTH) {
            return false;
        }
        int sum = 0;
        for (int i = 0; i < chars.length - 1; i++) {
            int num = chars[i] + CHAR_AND_NUMBER_OFFSET;
            sum += (num * NUMBER_WEIGHT[i]);
        }
        int mod = sum % MOD_MAP.length;
        char validateStr = MOD_MAP[mod];
        return validateStr == chars[ID_NUMBER_LENGTH - 1];
    }
}
